# import numpy as np
# from scipy import signal
# from skimage import data
# from matplotlib import pyplot as plt
# # 定义二维灰度图像的空间滤波函数
# def correl2d(img, window):
#     # 使用滤波器实现图像的空间相关
#     # mode = ‘same’ 表示输出尺寸等于输入尺寸
#     # boundary ='fill'表示滤波前，用常量值填充原图像的边缘，默认常量值为0
#     s = signal.correlate2d(img, window, mode ='same',boundary ='fill')
#     return s.astype(np.uint8)
 
# # img为原始图像
# img = data.camera()
# # 3*3盒状滤波模板
# window1 = np.ones((3, 3)) / (3 ** 2)
# # 5*5盒状滤波模板
# window2 = np.ones((5, 5)) / (5 ** 2)
# # 9*9盒状滤波模板
# window3 = np.ones((9, 9)) / (9 ** 2)
# # 生成滤波结果
# new_img1 = correl2d(img, window1)
# new_img2 = correl2d(img, window2)
# new_img3 = correl2d(img, window3)
# # 显示图像
# plt.rcParams['font.sans-serif'] = ['SimHei'] 
# plt.rcParams['axes.unicode_minus'] = False
# plt.subplot(2, 2, 1)
# plt.axis('off')
# plt.imshow(img, cmap = 'gray')
# plt.title('原图像')
# plt.subplot(2, 2, 2)
# plt.axis('off')
# plt.imshow(new_img1, cmap = 'gray')
# plt.title('3*3')
# plt.subplot(2, 2, 3)
# plt.axis('off')
# plt.imshow(new_img2, cmap = 'gray')
# plt.title('5*5')
# plt.subplot(2, 2, 4)
# plt.axis('off')
# plt.imshow(new_img3, cmap = 'gray')
# plt.title('9*9')
# # plt.savefig('盒状滤波结果.tif')
# plt.show()





import numpy as np
from scipy import signal
from skimage import data, color, io
from matplotlib import pyplot as plt

# 定义二维灰度图像的空间滤波函数
def correl2d(img, window):
    # 使用滤波器实现图像的空间相关
    s = signal.correlate2d(img, window, mode='same', boundary='fill')
    # 归一化处理
    s = (s - s.min()) / (s.max() - s.min()) * 255
    return s.astype(np.uint8)

# 读取图像并转换为灰度图像
img = io.imread(r'c:\Users\HP\Desktop\python\lena.jpg')  
img = color.rgb2gray(img)

# 打印原始图像信息
print("原始图像数据类型:", img.dtype)
print("原始图像形状:", img.shape)

# 盒状滤波模板
window1 = np.ones((3, 3)) / (3 ** 2)
window2 = np.ones((5, 5)) / (5 ** 2)
window3 = np.ones((7, 7)) / (7 ** 2)
window4 = np.ones((9, 9)) / (9 ** 2)

# 生成滤波结果
new_img1 = correl2d(img, window1)
new_img2 = correl2d(img, window2)
new_img3 = correl2d(img, window3)
new_img4 = correl2d(img, window4)

# 显示图像
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False
plt.subplot(3, 2, 1)
plt.axis('off')
plt.imshow(img, cmap='gray')
plt.title('原图像')

plt.subplot(3, 2, 2)
plt.axis('off')
plt.imshow(new_img1, cmap='gray')
plt.title('3x3')

plt.subplot(3, 2, 3)
plt.axis('off')
plt.imshow(new_img2, cmap='gray')
plt.title('5x5')

plt.subplot(3, 2, 4)
plt.axis('off')
plt.imshow(new_img3, cmap='gray')
plt.title('7x7')

plt.subplot(3, 2, 5)
plt.axis('off')
plt.imshow(new_img4, cmap='gray')
plt.title('9x9')

plt.show()



